package com.yanhao.viewmode

import androidx.lifecycle.LiveData
import com.yanhao.bean.UserInfo
import com.yanhao.utils.MMKVUtils

class UserInfoLivedata : LiveData<UserInfo>() {

    val userInfoManager = UserInfoManager()
    val listener = object : UserInfoManager.OnUserInfoDataChangeListener {
        override fun change(userInfo: UserInfo) {
            postValue(userInfo)
        }
    }

    init {
        postValue(MMKVUtils.getUserInfo())
    }

    fun postData(mUserInfo: UserInfo) {
        postValue(mUserInfo)
    }

    override fun onActive() {
        super.onActive()
        userInfoManager.setListener(listener)
    }

    override fun onInactive() {
        super.onInactive()
        userInfoManager.removeListener(listener)
    }

    companion object {
        private lateinit var userInfoLivedata: UserInfoLivedata
        fun getInstance(): UserInfoLivedata {
            userInfoLivedata =
                if (::userInfoLivedata.isInitialized) userInfoLivedata else UserInfoLivedata()
            return userInfoLivedata
        }
    }

}